<template>
    <div class="scrolling-notice">
        <div ref="noticeWrapper" class="notice-wrapper">
            <div
                ref="noticeContent"
                class="notice-content"
                :style="{ transform: `translateX(-${scrollPos}px)` }"
            >
                <span v-for="(msg, index) in messages" :key="index">{{
                    msg
                }}</span>
            </div>
        </div>
    </div>
</template>

<script>
import { ref, watchEffect } from "vue";

export default {
    name: "ScrollingNotice",
    props: {
        messages: {
            type: Array,
            required: true,
        },
        speed: {
            type: Number,
            default: 30,
        },
    },
    setup(props) {
        // 通知内容容器的宽度
        const noticeWrapperWidth = ref(0);
        // 通知内容区域的宽度
        const noticeContentWidth = ref(0);
        // 当前滚动位置
        const scrollPos = ref(0);
        // 自动滚动定时器
        let timer = null;

        // 监听窗口变化，更新通知内容容器和内容区域的宽度
        const noticeWrapperRef = ref(null);
        const noticeContentRef = ref(null);
        watchEffect(() => {
            noticeWrapperWidth.value = noticeWrapperRef.offsetWidth;
            noticeContentWidth.value = noticeContentRef.offsetWidth;
            console.log(noticeWrapperWidth.value, noticeContentWidth.value);
        });

        // 开始自动滚动
        const startAutoScroll = () => {
            timer = setInterval(() => {
                scrollPos.value += 1;
                if (scrollPos.value >= 320) {
                    scrollPos.value = 0;
                    console.log(1);
                }
            }, props.speed);
        };

        // 停止自动滚动
        const stopAutoScroll = () => {
            clearInterval(timer);
        };

        // 组件挂载时开始自动滚动
        startAutoScroll();

        return {
            noticeWrapperWidth,
            noticeContentWidth,
            scrollPos,
            startAutoScroll,
            stopAutoScroll,
        };
    },
};
</script>

<style scoped>
.scrolling-notice {
    position: relative;
    height: 40px;
    overflow: hidden;
}
.notice-wrapper {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    padding: 0 20px;
    white-space: nowrap;
    overflow: hidden;
    color: #fff;
}
.notice-content {
    position: absolute;
    top: 0;
    left: 0;
    white-space: nowrap;
    transition: none;
    display: inline-block;
    font-size: 14px;
    padding-left: 50px;

    /* transform: translateX(-{{scrollPos}}px); */
}
</style>
